﻿using System;
using System.Collections.Generic;
using System.Linq;
using Autodesk.Revit.Attributes;
using Autodesk.Revit.DB;
using Autodesk.Revit.UI;
using Autodesk.Revit.UI.Selection;
using YArchitech.Controls;

namespace SystemDiagramNew
{
	[Transaction(TransactionMode.Manual)]
	[Regeneration(RegenerationOption.Manual)]
	public class SystemDiagramAnnotate : IExternalCommand
	{
		private ExternalCommandData CommandData { get; set; }

		private UIDocument UIDocument
		{
			get
			{
				return this.CommandData.Application.ActiveUIDocument;
			}
		}

		private Document Document
		{
			get
			{
				return this.UIDocument.Document;
			}
		}

		private Autodesk.Revit.DB.View CurrentView
		{
			get
			{
				return this.UIDocument.ActiveView;
			}
		}

		private Selection Selection
		{
			get
			{
				return this.UIDocument.Selection;
			}
		}

		public string ErrorMessage { get; set; }

		private IEnumerable<Element> AllElements { get; set; }

		private IEnumerable<Element> MovedElements { get; set; }

		public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
		{
			this.CommandData = commandData;
			if (!this.TestEnvironment())
			{
				YJKMessageBox.Show(this.ErrorMessage);
				return Autodesk.Revit.UI.Result.Cancelled;
			}
			Result result;
			try
			{
				if (!this.Run())
				{
					YJKMessageBox.Show(this.ErrorMessage);
					result = Autodesk.Revit.UI.Result.Cancelled;
				}
				else
				{
					result = Autodesk.Revit.UI.Result.Succeeded;
				}
			}
			catch (Exception ex)
			{
				this.ErrorMessage = ex.Message;
				YJKMessageBox.Show(this.ErrorMessage);
				result = Autodesk.Revit.UI.Result.Cancelled;
			}
			return result;
		}

		private bool TestEnvironment()
		{
			if (!(this.CurrentView is ViewDrafting))
			{
				this.ErrorMessage = "请在绘制视图运行此命令！";
				return false;
			}
			this.AllElements = this.Document.GetElementsByView(this.CurrentView);
			if (!this.AllElements.Any<Element>())
			{
				this.ErrorMessage = "此实体不包含任何系统图实体!";
				return false;
			}
			return true;
		}

		private bool Run()
		{
			new SystemDiagramManager(this.CommandData).LabelPipeDiameter2();
			return true;
		}
	}
}
